package com.zmj.sy.mom.srv.aps.service;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zmj.sy.mom.srv.aps.bean.dto.completeReport.IntegralityDto;
import com.zmj.sy.mom.srv.aps.bean.dto.completeReport.NestQgFjInfoDto;
import com.zmj.sy.mom.srv.aps.bean.dto.completeReport.OrderCompDto;
import com.zmj.sy.mom.srv.aps.bean.entity.mes.WorkRecord;
import com.zmj.sy.mom.srv.aps.bean.entity.order.Order;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BasePageResVo;
import com.zmj.sy.mom.srv.aps.bean.vo.base.Result;
import com.zmj.sy.mom.srv.aps.bean.vo.completeReport.*;
import com.zmj.sy.mom.srv.aps.mapper.CompleteReportMapper;
import com.zmj.sy.mom.srv.aps.mapper.OrderMapper;
import com.zmj.sy.mom.srv.aps.mapper.WorkRecordMapper;
import com.zmj.sy.mom.srv.aps.utils.PkgUtils;
import com.zmj.sy.mom.srv.aps.utils.SyExceptionUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@RequiredArgsConstructor
@Service
public class CompleteReportService {

    private final CompleteReportMapper baseMapper;

    private final OrderMapper orderMapper;

    private final WorkRecordMapper workRecordMapper;

    /**
     * @Description: 获取在产订单列表
     *
     * @author: hejiahui
     * @since: 2024/9/5 11:24
     */
    public List<String> getOrderList(String orderNo) {
        List<String> list = new ArrayList<>();
        List<Order> orderList = orderMapper.lambdaQuery().like(StringUtils.isNotBlank(orderNo), Order::getOrderCode, orderNo).in(Order::getOrderType, 1, 3, 4).list();
        if (ObjectUtils.isNotEmpty(orderList)) {
            list = orderList.stream().map(Order::getOrderCode).distinct().collect(Collectors.toList());
        }
        return list;
    }
    /**
     * @Description: 获取订单齐套性详情
     *
     * @author: hejiahui
     * @since: 2024/9/5 14:46
     */
    public BasePageResVo<AssemOrderVo> getAssemOrderList(OrderCompDto dto) throws Exception {
        //获取订单下所有组件，及组件下的零组件

        // 三大件走原本逻辑，侧护板、连杆、推杆、护帮走 level = 2
        QueryWrapper<?> infoQuery = Wrappers.query();
        infoQuery.eq("ord.order_code", dto.getOrderNo());
        infoQuery.in("ord.order_type", 1, 3, 4);
        infoQuery.and(e->e.in("ord.suffix", "D","Y","Z") // 三大件
                .or()
                .notIn("ord.suffix", "D","Y","Z").eq("parBom.`level`", 2)); // 侧护板、连杆、推杆、护帮
        List<AssemOrderVo> assembleList = baseMapper.getAssBomInfo(infoQuery).stream().filter(CompleteReportService::filterAssem).collect(Collectors.toList());
        if (CollUtil.isEmpty(assembleList)) {
            return new BasePageResVo<>(assembleList.size(), assembleList);
        }
        //获取组件子集
        List<Integer> idList = assembleList.stream().map(AssemOrderVo::getId).collect(Collectors.toList());
        QueryWrapper<?> sonQuery = Wrappers.query();
        sonQuery.eq("ord.order_code", dto.getOrderNo());
        sonQuery.in("ord.order_type", 1, 3, 4);
        sonQuery.in("parBom.pid", idList);
        String[] typeStr = {"Platepart", "Assembly"};
        sonQuery.in("parBom.mater_type", Arrays.asList(typeStr));
        List<CompleteReportBomInfo> sonList = baseMapper.getBomInfo(sonQuery);
        Map<Integer, List<CompleteReportBomInfo>> pinMap = sonList.stream().collect(Collectors.groupingBy(CompleteReportBomInfo::getPid));

        //获取组件的子组件
        List<Integer> assemList = assembleList.stream().map(AssemOrderVo::getId).collect(Collectors.toList());
        QueryWrapper<?> assemQuery = Wrappers.query();
        assemQuery.eq("ord.order_code", dto.getOrderNo());
        assemQuery.eq("parBom.mater_type", "Assembly");
        List<CompleteReportBomInfo> sonAssemList = baseMapper.getBomInfo(assemQuery);
        Map<Integer, List<CompleteReportBomInfo>> pinAssemMap = sonAssemList.stream().filter(e -> e.getPid() != null).collect(Collectors.groupingBy(CompleteReportBomInfo::getPid));

        //切割
        QueryWrapper<?> cuttingQuery = Wrappers.query();
        cuttingQuery.eq("ord.order_code", dto.getOrderNo());
        final List<String> cuttingPhase = Arrays.asList("JG", "HG");
        cuttingQuery.in(" det.phase_code", cuttingPhase);
        cuttingQuery.isNotNull("bom.pid");
        List<CompleteReportPhaseFinishedInfo> cuttingList = baseMapper.getPhaseFinishedInfo(cuttingQuery);

        //完焊
        QueryWrapper<?> whQuery = Wrappers.query();
        whQuery.eq("ord.order_code", dto.getOrderNo());
        whQuery.eq(" det.phase_code", "WH");
        List<CompleteReportPhaseFinishedInfo>  whList = baseMapper.getPhaseFinishedInfo(whQuery);
        Map<Integer, List<CompleteReportPhaseFinishedInfo>> whSonIdMap = whList.stream().collect(Collectors.groupingBy(CompleteReportPhaseFinishedInfo::getSonId));

        //获取钢板领料情况
/*        List<Map<String, Object>> cuttingListDetail = baseMapper.getPhaseFinishedInfoDetail(cuttingQuery);
        Map<Integer, List<Map<String, Object>>> nestPlanId = new HashMap<>();
        if (ObjectUtils.isNotEmpty(cuttingListDetail)) {
            Set<Integer> detId = cuttingListDetail.stream().map(e -> (Integer)e.get("detId")).collect(Collectors.toSet());
            QueryWrapper<?> partPickQuery = Wrappers.query();
            partPickQuery.in("npart.nest_plan_id", detId);
            partPickQuery.ge("ppick.plate_state", 4);
            List<Map<String, Object>> partPickList = baseMapper.getPartPickList(partPickQuery);
            nestPlanId = partPickList.stream().collect(Collectors.groupingBy(e -> Integer.parseInt( e.get("nest_plan_id").toString())));
        }*/
        QueryWrapper<?> llQuery = Wrappers.query();
        llQuery.eq("ord.order_code", dto.getOrderNo());
        llQuery.eq(" det.phase_code", "LL");
        List<CompleteReportPhaseFinishedInfo>  llList = baseMapper.getPhaseFinishedInfo(llQuery);

        //零组件整体完成情况
        QueryWrapper<?> ZeroFinishedQuery = Wrappers.query();
        ZeroFinishedQuery.eq("ord.order_code", dto.getOrderNo());
        ZeroFinishedQuery.ne("bom.mater_type", "Component");
        List<Map<String, Object>> zeroList = baseMapper.getZeroFinishedInfo(ZeroFinishedQuery);
        Map<Object, List<Map<String, Object>>> zeroPidMap = zeroList.stream().filter(e -> ObjectUtils.isNotEmpty(e.get("pid"))).collect(Collectors.groupingBy(e -> e.get("pid")));
        Map<Object, List<Map<String, Object>>> zeroSonMap = zeroList.stream().collect(Collectors.groupingBy(e -> e.get("sonId")));
        //外购件完成情况
        QueryWrapper<?> wlQuery = Wrappers.query();
        wlQuery.eq("ord.order_code", dto.getOrderNo());
        wlQuery.eq("bom.mater_type", "Component");
        List<Map<String, Object>> wlList = baseMapper.getZeroFinishedInfo(wlQuery);
//        Map<Object, List<Map<String, Object>>> wlPidMap = wlList.stream().filter(e -> ObjectUtils.isNotEmpty(e.get("pid"))).collect(Collectors.groupingBy(e -> e.get("pid")));
        for (AssemOrderVo vo : assembleList) {
            if (pinMap.containsKey(vo.getId())) {
                //获取子集下的组件
                List<Integer> sonAssemIdList = this.getSonAssemIdList(vo.getId(), pinAssemMap);
                //领料完成数量
                Map<String, List<CompleteReportPhaseFinishedInfo>> llPartMap = llList.stream().filter(e -> sonAssemIdList.contains(e.getPid())).collect(Collectors.groupingBy(CompleteReportPhaseFinishedInfo::getPlm));
                List<CompleteReportPhaseFinishedInfo> llDistList = new ArrayList<>();
                //左右件求平均值
                for (String key : llPartMap.keySet()) {
                    CompleteReportPhaseFinishedInfo llMap = new CompleteReportPhaseFinishedInfo();
                    List<CompleteReportPhaseFinishedInfo> completeReportPhaseFinishedInfos = llPartMap.get(key);
                    BeanUtils.copyProperties(completeReportPhaseFinishedInfos.get(0),llMap);
                    int finCnt = (completeReportPhaseFinishedInfos.stream().mapToInt(e -> e.getFinCnt().intValue()).sum()) / completeReportPhaseFinishedInfos.size();
                    llMap.setFinCnt(new BigDecimal(finCnt));
                    llDistList.add(llMap);
                }
                CompleteReportPhaseFinishedInfo llMap = llDistList.stream().min(Comparator.comparing(CompleteReportPhaseFinishedInfo::getFinCnt)).get();
                vo.setAssemReadyForPickCut(llMap.getFinCnt().intValue());
                //切割完成配套数量
                Map<String, List<CompleteReportPhaseFinishedInfo>> cuttingPartMap = cuttingList.stream().filter(e -> sonAssemIdList.contains(e.getPid())).collect(Collectors.groupingBy(CompleteReportPhaseFinishedInfo::getPlm));
                List<CompleteReportPhaseFinishedInfo> cuttingDistList = new ArrayList<>();
                //左右件求平均值
                for (String key : cuttingPartMap.keySet()) {
                    CompleteReportPhaseFinishedInfo cuttingMap = new CompleteReportPhaseFinishedInfo();
                    List<CompleteReportPhaseFinishedInfo> completeReportPhaseFinishedInfos = cuttingPartMap.get(key);
                    BeanUtils.copyProperties(completeReportPhaseFinishedInfos.get(0),cuttingMap);
                    int finCnt = (completeReportPhaseFinishedInfos.stream().mapToInt(e -> e.getFinCnt().intValue()).sum()) / completeReportPhaseFinishedInfos.size();
                    cuttingMap.setFinCnt(new BigDecimal(finCnt));
                    cuttingDistList.add(cuttingMap);
                }

                CompleteReportPhaseFinishedInfo cuttingMap = cuttingDistList.stream().min(Comparator.comparing(CompleteReportPhaseFinishedInfo::getFinCnt)).get();
                vo.setAssemCutReadySetCnt(cuttingMap.getFinCnt().intValue());
                //外领件完成情况
                List<Map<String, Object>> partWlList = wlList.stream().filter(e -> sonAssemIdList.contains((Integer)e.get("pid"))).collect(Collectors.toList());
                if (CollUtil.isEmpty(partWlList)) {
                    vo.setWlFinishCnt("-.-");
                } else {
                    Map<String, List<Map<String, Object>>> wlPartMap = partWlList.stream().collect(Collectors.groupingBy(e -> (String) e.get("plm")));
                    List<Map<String, Object>> wlPartList = new ArrayList<>();
                    //左右件求平均值
                    for (String key : wlPartMap.keySet()) {
                        Map<String, Object> wlMap = new HashMap<>();
                        List<Map<String, Object>> completeReportPhaseFinishedInfos = wlPartMap.get(key);
                        BeanUtils.copyProperties(completeReportPhaseFinishedInfos.get(0),wlMap);
                        int finCnt = (completeReportPhaseFinishedInfos.stream().mapToInt(e -> ((BigDecimal)e.get("finCnt")).intValue()).sum()) / completeReportPhaseFinishedInfos.size();
                        wlMap.put("finCnt", new BigDecimal(finCnt));
                        wlPartList.add(wlMap);
                    }
                    Map<String, Object> minWlPap = wlPartList.stream().min(Comparator.comparing(e -> new BigDecimal(e.get("finCnt").toString()))).get();
                    vo.setWlFinishCnt(minWlPap.get("finCnt").toString());
                }
                //加工供拼焊配套数量
//                List<Map<String, Object>> partZeroList = zeroPidMap.get(vo.getId());
                List<Map<String, Object>> partZeroList = zeroPidMap.get(vo.getId()).stream()
                        .filter(e -> !e.get("plm").toString().contains("P1") && !e.get("plm").toString().contains("P2") && !e.get("plm").toString().contains("P3") &&
                                !e.get("plm").toString().contains("P4") && !e.get("plm").toString().contains("P5") && !e.get("plm").toString().contains("P6") &&
                                !e.get("plm").toString().contains("PDB")
                                ).collect(Collectors.toList());
                if (ObjectUtils.isNotEmpty(partZeroList)) {
                    //-010105_逻辑变更
                    Boolean ifChange = false;
                    for (Map<String, Object> stringObjectMap : partZeroList) {
                        if ( stringObjectMap.get("plm").toString().contains("-010105_")) {
                            ifChange = true;
                        }
                    }
                    if (ifChange) {
                        List<Map<String, Object>> targetPlms = partZeroList.stream().filter(e -> e.get("plm").toString().contains("-010105_")).collect(Collectors.toList());
                        for (Map<String, Object> targetPlm : targetPlms) {
                            String plm = targetPlm.get("plm").toString();
                            Integer sonId = (Integer)targetPlm.get("sonId");
                            partZeroList = partZeroList.stream().filter(e -> !e.get("plm").toString().equals(plm)).collect(Collectors.toList());
                            List<Map<String, Object>> maps = zeroPidMap.get(sonId);
                            if (ObjectUtils.isNotEmpty(maps)) {
                                partZeroList.addAll(maps);
                            }
                        }
                    }
                    Map<String, Object> preparedMap = partZeroList.stream().min(Comparator.comparing(e -> new BigDecimal(e.get("finCnt").toString()))).get();
                    vo. setAssemPreparedSetCnt(preparedMap.get("finCnt").toString());
                }else {
                    vo.setAssemPreparedSetCnt("/");
                }

                //拼焊供整加配套数量
                List<CompleteReportPhaseFinishedInfo> whThisList = whSonIdMap.get(vo.getId());
                if (CollUtil.isNotEmpty(whThisList)) {
                    int readyForMachCnt = whThisList.get(0).getFinCnt().intValue();
                    vo.setAssemReadyForMachCnt(String.valueOf(readyForMachCnt));
                } else {
                    vo.setAssemReadyForMachCnt("-.-");
                }
                //完工供总装配套数量
                List<Map<String, Object>> readyForPaintList = zeroSonMap.get(vo.getId());
                if (CollUtil.isNotEmpty(readyForPaintList)) {
                    Integer readyForPaintCnt = new BigDecimal(readyForPaintList.get(0).get("finCnt").toString()).intValue();
                    vo.setAssemReadyForPaintCnt(readyForPaintCnt.toString());
                }else {
                    vo.setAssemReadyForPaintCnt("-.-");
                }
            } else {
                vo.setAssemReadyForPickCut(0);
                vo.setAssemCutReadySetCnt(0);
                vo.setAssemPreparedSetCnt("0");
                vo.setAssemReadyForMachCnt("-.-");
                vo.setAssemReadyForPaintCnt("-.-");
            }
        }
        return new BasePageResVo<>(assembleList.size(), assembleList);
    }
    /**
     * @Description: 获取组件下子孙组件
     *
     * @author: hejiahui
     * @since: 2025/1/7 11:45
     */
    private List<Integer> getSonAssemIdList(Integer id, Map<Integer, List<CompleteReportBomInfo>> pinAssemMap) {
        List<Integer> AssemIdList = new ArrayList<>();
        AssemIdList.add(id);
        List<Integer> checkList = new ArrayList<>();
        checkList.add(id);
        while (ObjectUtils.isNotEmpty(checkList)){
            Integer firstAssem = checkList.get(0);
            List<CompleteReportBomInfo> sonList = pinAssemMap.get(firstAssem);
            if (ObjectUtils.isNotEmpty(sonList)) {
                sonList.forEach(e -> {
                    checkList.add(e.getSonId());
                    AssemIdList.add(e.getSonId());
                });
            }
            checkList.remove(0);
        }
        return AssemIdList;
    }

    /**
     * 是否为重要组件
     * @param assem
     * @return
     */
    private static boolean filterAssem(AssemOrderVo assem) {

        if (org.springframework.util.StringUtils.hasText(assem.getOrderSuffix()) && assem.getOrderSuffix().equals("B")) {
            return true;
        }

        if(assem.getAssemPLMID() != null && assem.getAssemPLMID().startsWith("ZT")){
            return false;
        }

        if (assem.getAssemPLMID() != null && assem.getAssemPLMID().matches("^.+(P1|P2|P3|P4|P5|P6|PDB|-0103|-0102|-0202|-0203).*$")) {
            return true;
        }

        if (org.springframework.util.StringUtils.hasText(assem.getOrderSuffix())
                && (assem.getOrderSuffix().equals("L") || assem.getOrderSuffix().equals("T") || assem.getOrderSuffix().equals("B"))
                && (assem.getAssemInfotxt().contains("前连杆") || assem.getAssemInfotxt().contains("后连杆") || assem.getAssemInfotxt().contains("推杆体")  || assem.getAssemInfotxt().contains("级护帮") )) {
            return true;
        }

        if (assem.getAssemInfotxt() == null) {
            return false;
        }

        return Stream.of("拼", "左侧护板", "右侧护板", "挡板组件").anyMatch(assem.getAssemInfotxt()::contains);
    }

    /**
     * @Description: 组件下的零件领料完成齐套数量
     *
     * @author: hejiahui
     * @since: 2024/10/31 14:00
     */
    private Integer getPickCut(AssemOrderVo vo, List<Map<String, Object>> cuttingListDetail, Map<Integer, List<Map<String, Object>>> nestPlanId) {
        if (ObjectUtils.isEmpty(cuttingListDetail)) {
            return 0;
        }
        Map<Integer, List<Map<String, Object>>> sonIdMaps = cuttingListDetail.stream().filter(e -> ((Integer) e.get("pid")).equals(vo.getId())).collect(Collectors.groupingBy(e -> (Integer) e.get("sonId")));
        if (sonIdMaps.isEmpty()) {
            return 0;
        }
        int minCut = Integer.MAX_VALUE;
        for (Integer sonId : sonIdMaps.keySet()) {
            List<Map<String, Object>> sonDetails = sonIdMaps.get(sonId);
            int pickCnt = 0;
            for (Map<String, Object> sonDetail : sonDetails) {
                int totalCnt = new BigDecimal(sonDetail.get("total_count").toString()).intValue();
                List<Map<String, Object>> detail = nestPlanId.get((Integer) sonDetail.get("detId"));
                if (ObjectUtils.isNotEmpty(detail)) {
                    pickCnt += (new BigDecimal(detail.get(0).get("totalCnt").toString()).intValue())/totalCnt;
                }
            }
            if (pickCnt < minCut) {
                minCut = pickCnt;
            }
        }
        return minCut;
    }
    /**
     * @Description: 获取物料齐套性详情
     *
     * @author: hejiahui
     * @since: 2024/9/7 15:38
     */
    public BasePageResVo<IntegralityVo> getOrderCompDetail(IntegralityDto dto) {
        BasePageResVo<IntegralityVo> page = BasePageResVo.empty();
        //获取组件信息
        QueryWrapper<?> orderBomQuery = new QueryWrapper<>();
        orderBomQuery.eq("ord.order_code", dto.getOrderNo());
        orderBomQuery.eq("bom.plm_id", dto.getPlmid());
        List<Map<String, Object>> assembleList = baseMapper.getOrderBom(orderBomQuery);
        if (ObjectUtils.isEmpty(assembleList)) {
            throw SyExceptionUtils.e("未找到该订单信息");
        }else if (assembleList.size() > 1) {
            throw SyExceptionUtils.e("该订单信息不唯一");
        }
        String parentPath = assembleList.get(0).get("assembly_path").toString();
        if (dto.getSortType().equals(1)) {
            //切割齐套
            QueryWrapper<?> cuttingWrapper = new QueryWrapper<>();
            cuttingWrapper.eq("ord.order_code", dto.getOrderNo());
            cuttingWrapper.likeRight("bom.assembly_path", parentPath);
            cuttingWrapper.like(StringUtils.isNotBlank(dto.getSonPlmid()),"bom.plm_id" , dto.getSonPlmid());
            cuttingWrapper.like(StringUtils.isNotBlank(dto.getParentPlmid()), "pBom.plm_id", dto.getParentPlmid());
            cuttingWrapper.in(dto.getPackageNo() != null && !dto.getPackageNo().isEmpty(), "aord.seq", dto.getPackageNo());
            List<IntegralityVo> pageList = baseMapper.getCuttingInfo( cuttingWrapper);
            for (IntegralityVo record : pageList) {
                record.setPackageNo(PkgUtils.gen(Integer.parseInt(record.getPackageNo())));
                record.setPackNum(new BigDecimal(record.getPackNum().toString()).intValue());
            }
            page = new BasePageResVo<>(pageList.size(), pageList);
        } else if (dto.getSortType().equals(2)) {
            //加工齐套
            QueryWrapper<?> processWrapper = new QueryWrapper<>();
            processWrapper.eq("ord.order_code", dto.getOrderNo());
            processWrapper.likeRight("bom.assembly_path", parentPath);
            processWrapper.notLike("bom.plm_id ", "P1");
            processWrapper.notLike("bom.plm_id ", "P2");
            processWrapper.notLike("bom.plm_id ", "P3");
            processWrapper.notLike("bom.plm_id ", "P4");
            processWrapper.notLike("bom.plm_id ", "P5");
            processWrapper.notLike("bom.plm_id ", "P6");
            processWrapper.notLike("bom.plm_id ", "PDB");
            processWrapper.like(StringUtils.isNotBlank(dto.getSonPlmid()), "bom.plm_id", dto.getSonPlmid());
            processWrapper.like(StringUtils.isNotBlank(dto.getParentPlmid()), "pBom.plm_id", dto.getParentPlmid());
//            processWrapper.in(dto.getPackageNo() != null && !dto.getPackageNo().isEmpty(), "aord.seq", dto.getPackageNo());
//            List<IntegralityVo> pageList = baseMapper.getProcessInfo( processWrapper);
            List<IntegralityVo> pageList = baseMapper.getProcessInfoNoPkg( processWrapper);
//            for (IntegralityVo record : pageList) {
//                record.setPackageNo(PkgUtils.gen(Integer.parseInt(record.getPackageNo())));
//                record.setPackNum(new BigDecimal(record.getPackNum().toString()).intValue());
//            }
            page = new BasePageResVo<>(pageList.size(), pageList);
        } else if (dto.getSortType().equals(4)) {
            //外购件详情
            QueryWrapper<?> wlWrapper = new QueryWrapper<>();
            wlWrapper.eq("ord.order_code", dto.getOrderNo());
            wlWrapper.likeRight("bom.assembly_path", parentPath);
            wlWrapper.like(StringUtils.isNotBlank(dto.getSonPlmid()), "bom.plm_id", dto.getSonPlmid());
            wlWrapper.like(StringUtils.isNotBlank(dto.getParentPlmid()), "pBom.plm_id", dto.getParentPlmid());
//            wlWrapper.in(dto.getPackageNo() != null && !dto.getPackageNo().isEmpty(), "aord.seq", dto.getPackageNo());
            List<IntegralityVo> pageList = baseMapper.getWlInfo(wlWrapper);
//            for (IntegralityVo record : pageList) {
//                record.setPackageNo(PkgUtils.gen(Integer.parseInt(record.getPackageNo())));
//                record.setPackNum(new BigDecimal(record.getPackNum().toString()).intValue());
//            }
            page = new BasePageResVo<>(pageList.size(), pageList);
        }else if (dto.getSortType().equals(5)) {
            //领料详情
            QueryWrapper<?> cuttingWrapper = new QueryWrapper<>();
            cuttingWrapper.eq("ord.order_code", dto.getOrderNo());
            cuttingWrapper.likeRight("bom.assembly_path", parentPath);
            cuttingWrapper.like(StringUtils.isNotBlank(dto.getSonPlmid()),"bom.plm_id" , dto.getSonPlmid());
            cuttingWrapper.like(StringUtils.isNotBlank(dto.getParentPlmid()), "pBom.plm_id", dto.getParentPlmid());
            cuttingWrapper.in(dto.getPackageNo() != null && !dto.getPackageNo().isEmpty(), "aord.seq", dto.getPackageNo());
            List<IntegralityVo> pageList = baseMapper.getLlInfo( cuttingWrapper);
            for (IntegralityVo record : pageList) {
                record.setPackageNo(PkgUtils.gen(Integer.parseInt(record.getPackageNo())));
                record.setPackNum(new BigDecimal(record.getPackNum().toString()).intValue());
            }
            page = new BasePageResVo<>(pageList.size(), pageList);
        } else {
            return page;
        }
        return page;
    }
    /**
     * @Description: 获取零件套料，分拣，切割进度
     *
     * @author: hejiahui
     * @since: 2024/9/5 14:46
     */
    public List<NestQgFjInfoVo> getNestQgFjInfo(NestQgFjInfoDto dto) {
        //套料信息
        QueryWrapper<?> nestWrapper = new QueryWrapper<>();
        nestWrapper.eq("part_id", dto.getPlmid());
        List<Map<String, Object>> nestList = baseMapper.getNestInfo(nestWrapper);
        //切割
        QueryWrapper<?> cuttingWrapper = new QueryWrapper<>();
        cuttingWrapper.eq("plmid", dto.getPlmid());
        List<Map<String, Object>> cuttingList = baseMapper.getCuttingListInfo(cuttingWrapper);
        Map<Object, Map<String, Object>> cuttingMap = new HashMap<>();
        if (ObjectUtils.isNotEmpty(cuttingList)) {
            cuttingMap = cuttingList.stream().collect(Collectors.toMap(e -> (String)e.get("pallet_number"), e -> e, (v1, v2) -> v1));
        }
        //分拣装盘
        QueryWrapper<?> sortWrapper = new QueryWrapper<>();
        sortWrapper.eq("plmid", dto.getPlmid());
        List<Map<String, Object>> sortList = baseMapper.getSortInfo(sortWrapper);
        Map<Object, Map<String, Object>> sortMap = new HashMap<>();
        if (ObjectUtils.isNotEmpty(sortList)) {
            sortMap = sortList.stream().collect(Collectors.toMap(e ->  (String)e.get("attr"), e -> e, (v1, v2) -> v1));
        }
        //数据汇总
        List<NestQgFjInfoVo> nestQgFjInfoVos = new ArrayList<>();
        for (Map<String, Object> stringObjectMap : nestList) {
            NestQgFjInfoVo nestQgFjInfoVo = new NestQgFjInfoVo();
            nestQgFjInfoVo.setPlmid((String)stringObjectMap.get("part_id"));
            nestQgFjInfoVo.setPlateNum((String)stringObjectMap.get("plate_code"));
            nestQgFjInfoVo.setNestCnt(Integer.parseInt( stringObjectMap.get("nestCnt").toString()));
            nestQgFjInfoVo.setSortCnt1(Integer.parseInt( stringObjectMap.get("sortCnt1").toString()));
            Map<String, Object> thisCuttingMap = cuttingMap.get((String) stringObjectMap.get("plate_code"));
            if (ObjectUtils.isNotEmpty(thisCuttingMap)) {
                nestQgFjInfoVo.setCuttingCnt(Integer.parseInt( thisCuttingMap.get("cuttingCnt").toString()));
            }
            final Map<String, Object> thisSortMap = sortMap.get((String) stringObjectMap.get("plate_code"));
            if (ObjectUtils.isNotEmpty(thisSortMap)) {
                nestQgFjInfoVo.setSortCnt2(Integer.parseInt( thisSortMap.get("sortCnt2").toString()));
                nestQgFjInfoVo.setZpCnt(Integer.parseInt(thisSortMap.get("zpCnt").toString()));
            }
            nestQgFjInfoVos.add(nestQgFjInfoVo);
        }

        return nestQgFjInfoVos;
    }
    /**
     * @Description: 钢板报工记录完善
     *
     * @author: hejiahui
     * @since: 2024/9/5 11:24
     */
    public Result completePlateReport(List<String> plateList) {
//        List<String> plateList = new ArrayList<>();
//        if (!StringUtils.isBlank(plateNos)) {
//            final List<String> plateNoList = Arrays.asList(plateNos.split(","));
//            plateList.addAll(plateNoList);
//        } else {
//            //获取表里所有钢板
//            QueryWrapper<?> queryWrapper = new QueryWrapper<>();
//            List<Map<String, Object>> allPlateNo = baseMapper.getAllPlateNo(queryWrapper);
//            plateList.addAll(allPlateNo.stream().map(e -> (String) e.get("plate_code")).collect(Collectors.toList()));
//        }
        //一张一张钢板同步
        if ( ObjectUtils.isEmpty(plateList)) {
            return Result.success();
        }
        String errorLog = "";
        for (String plateNo : plateList) {
            //获取nest_part表数据
            QueryWrapper<?> nestPartWrapper = new QueryWrapper<>();
            nestPartWrapper.eq("plate_code", plateNo);
            List<Map<String, Object>> nestPartList = baseMapper.getNestPartPlateInfo(nestPartWrapper);
            if (ObjectUtils.isEmpty(nestPartList)) {
                continue;
            }
            //获取record表数据
            QueryWrapper<?> recordWrapper = new QueryWrapper<>();
            recordWrapper.eq("pallet_number", plateNo);
            List<Map<String, Object>> recordList = baseMapper.getRecordPlateInfo(recordWrapper);
            if (ObjectUtils.isEmpty(recordList)) {
                errorLog = errorLog + plateNo + ":报工记录表数据为空" + "\n";
                continue;
            }
            final Map<String, List<Map<String, Object>>> nestPartPlatePartMap = recordList.stream().collect(Collectors.groupingBy(e -> e.get("plateNo").toString() + e.get("partNo")));
            final List<String> cuttingPhase = Arrays.asList("JG", "HG");
            final List<WorkRecord> records = workRecordMapper.lambdaQuery()
                    .in(WorkRecord::getPhaseCode, cuttingPhase)
                    .eq(WorkRecord::getWorkType, 2)
                    .eq(WorkRecord::getType, 2)
                    .eq(WorkRecord::getPalletNumber, plateNo).list();
            final WorkRecord workRecord = records.get(0);
            //维护缺失数据
            for (Map<String, Object> nestPartMap : nestPartList) {
                final List<Map<String, Object>> maps = nestPartPlatePartMap.get(nestPartMap.get("plateNo").toString() + nestPartMap.get("partNo").toString());
                if (ObjectUtils.isEmpty(maps)) {
                    WorkRecord newRecord = new WorkRecord();
                    BeanUtils.copyProperties(workRecord, newRecord);
                    newRecord.setPlmid(nestPartMap.get("partNo").toString());
                    final int cnt = new BigDecimal(nestPartMap.get("partCnt").toString()).intValue();
                    newRecord.setTotalCount(cnt);
                    newRecord.setSuccessCount(cnt);
                    newRecord.setFailCount(0);
                    newRecord.setErpState(0);
                    newRecord.setApsWorkDetailId(null);
                    newRecord.setStorageNumber("hpl20250116");
                    workRecordMapper.insert(newRecord);
                }else {
                    final Map<String, Object> stringObjectMap = maps.get(0);
                    final int recordCnt = new BigDecimal(stringObjectMap.get("partCnt").toString()).intValue();
                    final int nestCnt = new BigDecimal(nestPartMap.get("partCnt").toString()).intValue();
                    if (recordCnt < nestCnt) {
                        WorkRecord newRecord = new WorkRecord();
                        BeanUtils.copyProperties(workRecord, newRecord);
                        newRecord.setPlmid(nestPartMap.get("partNo").toString());
                        int cnt = nestCnt - recordCnt;
                        newRecord.setTotalCount(cnt);
                        newRecord.setSuccessCount(cnt);
                        newRecord.setFailCount(0);
                        newRecord.setErpState(0);
                        newRecord.setApsWorkDetailId(null);
                        newRecord.setStorageNumber("hpl20250116");
                        workRecordMapper.insert(newRecord);
                    }
                }
            }

        }
        if (StringUtils.isNotBlank(errorLog)) {
            return Result.error(errorLog);
        } else {
            return Result.success();
        }
    }
}
